package com.crm.controller;

import com.crm.constant.Constant;
import com.crm.pojo.Right;
import com.crm.pojo.Role;
import com.crm.pojo.User;
import com.crm.service.role.RoleService;
import com.crm.service.user.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class LoginController {
    @Resource
    private UserService userService;
    @Resource
    private RoleService roleService;

    /**
     * 登录
     * @param usrName 用户名
     * @param usrPassword 用户密码
     * @param request 请求
     * @return 返回一个字符串路径
     * @throws Exception
     */
    @RequestMapping(value = "/doLogin")
    public String login(
            @RequestParam String usrName,
            @RequestParam String usrPassword,
            HttpServletRequest request
    ) throws Exception {
        try {
//            usrPassword = userService.encryptPassword(usrPassword); //封装之前先进行加密

            UsernamePasswordToken token = new UsernamePasswordToken(usrName, usrPassword);
            Subject subject = SecurityUtils.getSubject();
            subject.login(token);//认证、登录
            //认证(登录)成功
            User user = (User) subject.getPrincipal();

            //获取权限
            Role role = user.getRole(); //如果一对多关联不是立即加载，则需要通过用户获取
            List<Right> rights = roleService.findRightsByRole(role);
            role.getRights().addAll(rights);

            request.getSession().setAttribute(Constant.LOGIN_USER, user);
            return "redirect:/content";
        } catch (UnknownAccountException | IncorrectCredentialsException e) {
            request.setAttribute("msg", "用户名或密码错误，登录失败！");
            return "login";
        } catch (LockedAccountException e) {
            request.setAttribute("msg", "用户被禁用，登录失败！");
            return "login";
        } catch (AuthenticationException e) {
            request.setAttribute("msg", "认证异常，登录失败！");
            return "login";
        }
    }

    /**
     * 退出/注销
     * @param session
     * @return 返回一个字符串路径
     */
    @RequestMapping(value = "/logout")
    public String logout(HttpSession session) {
        session.removeAttribute(Constant.LOGIN_USER);
        SecurityUtils.getSubject().logout();//Shiro注销

        return "redirect:/login";
    }
}